﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack; // 需安装 HtmlAgilityPack NuGet包，用于HTML解析  

namespace h7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            string keyword = txtKeyword.Text.Trim();

            if (string.IsNullOrEmpty(keyword))
            {
                MessageBox.Show("请输入关键词");
                return;
            }

            btnSearch.Enabled = false;
            txtBaiduResult.Text = "加载中...";
            txtBingResult.Text = "加载中...";

            // 并发两个搜索任务  
            var baiduTask = SearchBaiduAsync(keyword);
            var bingTask = SearchBingAsync(keyword);

            // 等待两个任务完成  
            var baiduResult = await baiduTask;
            var bingResult = await bingTask;

            // 显示结果  
            txtBaiduResult.Text = baiduResult;
            txtBingResult.Text = bingResult;

            btnSearch.Enabled = true;
        }
        private async Task<string> SearchBaiduAsync(string keyword)
        {
            try
            {
                using (HttpClientHandler handler = new HttpClientHandler())
                {
                    // 可添加代理  
                    // handler.Proxy = new WebProxy("http://your-proxy:port");  
                    // handler.UseProxy = true;  

                    using (HttpClient client = new HttpClient(handler))
                    {
                        client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0 Safari/537.36");
                        client.DefaultRequestHeaders.Add("Referer", "https://www.baidu.com/");

                        string url = "https://www.baidu.com/s?wd=" + Uri.EscapeDataString(keyword);

                        string html = await client.GetStringAsync(url);

                        string text = ExtractTextFromHtml(html);

                        return TruncateText(text, 200);
                    }
                }
            }
            catch (Exception ex)
            {
                return "百度搜索出错：" + ex.Message;
            }
        }

        private async Task<string> SearchBingAsync(string keyword)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 必应搜索url示例  
                    string url = "https://www.bing.com/search?q=" + Uri.EscapeDataString(keyword);

                    string html = await client.GetStringAsync(url);

                    string text = ExtractTextFromHtml(html);

                    return TruncateText(text, 200);
                }
            }
            catch (Exception ex)
            {
                return "必应搜索出错：" + ex.Message;
            }
        }

        // 从HTML中简单提取文本内容（去除标签等）  
        private string ExtractTextFromHtml(string html)
        {
            var doc = new HtmlAgilityPack.HtmlDocument(); // 明确指定命名空间
            doc.LoadHtml(html);

            // 这里简化处理，提取<body>文本，实际可根据搜索结果页面DOM结构提取具体结果部分  
            var body = doc.DocumentNode.SelectSingleNode("//body");
            if (body == null)
                return "";

            // 只保留纯文本，去掉脚本、样式  
            foreach (var script in body.SelectNodes("//script|//style") ?? new HtmlNodeCollection(null))
            {
                script.Remove();
            }

            string text = body.InnerText;

            // 清理多余空白符  
            text = System.Text.RegularExpressions.Regex.Replace(text, @"\s+", " ").Trim();

            return text;
        }

        // 截取指定长度文本  
        private string TruncateText(string text, int maxLength)
        {
            if (string.IsNullOrEmpty(text))
                return "";

            if (text.Length <= maxLength)
                return text;

            return text.Substring(0, maxLength) + "...";
        }
    }
}
